<!--
 * @author  dumeng
 * 编辑课件
-->
<template>
  <div class="courseware-update">
    <div class="courseware-update-title">新建/编辑课件</div>
    <section v-loading="loading" class="courseware-update-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="form">
        <el-form-item label="课件名称" prop="subjectName">
          <el-input v-model.trim="form.subjectName" maxlength="100" placeholder="请输入课件名称" />
        </el-form-item>

        <el-form-item label="课件分类" prop="subjectClassify">
          <el-cascader v-if="showClassify" ref="classify" v-model="form.subjectClassify" style="width:100%" clearable :props="createClassifyProps" :options="classifyOptions" />
        </el-form-item>
        <el-form-item label="课件类型" prop="subjectType">
          <el-radio-group v-model="form.subjectType" disabled @change="changeFileAccept">
            <el-radio label="KCLX01">视频</el-radio>
            <el-radio label="KCLX03">音频</el-radio>
            <el-radio label="KCLX02">pdf文档</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课件上传" prop="courseId">
          <div :key="form.courseId" class="select-data">
            {{ '已上传' }}
          </div>
          <el-tooltip class="item" effect="dark" content="预览" placement="top">
            <i style="font-size: 16px;cursor: pointer;" class="el-icon-view" @click="handlePreview" />
          </el-tooltip>
        </el-form-item>
        <el-form-item :label="form.subjectType === 'KCLX02' ? '课件页数' : '课件时长'" prop="subjectDuration">
          <el-input v-model.number="form.subjectDuration" :disabled="inputDuration" :placeholder="`请输入课件${form.subjectType === 'KCLX02' ? '页数(页)' : '时长(秒)'}`" clearable>
            <template v-if="form.subjectDuration" slot="append">{{ fomatterTimeAndPage(form.subjectDuration) }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="课件封面">
          <template v-if="coverScreenshots.length > 0 && !form.subjectImg">
            <el-radio-group v-model="subjectImgType">
              <el-radio :label="1">从下列图片中选取</el-radio>
              <el-radio :label="2">自定义上传</el-radio>
            </el-radio-group>
            <el-card v-if="subjectImgType === 1" class="box-card">
              <div v-if="coverScreenshots.length" class="coverScreenshots-images">
                <div v-for="(item, index) in coverScreenshots" :key="`coverScreenshots${index}`" class="coverScreenshots-item" @click="selectCoverImg(item)">
                  <el-image style="width: 100%;height: auto;display: block;margin-bottom: 10px;" :src="'data:image/png;base64,'+item.fileBase64 " />
                </div>
              </div>
            </el-card>
          </template>
          <image-upload
            v-if="(form.subjectImg || subjectImgType === 2) && subjectImgType!==1"
            :key="uploadImg.imagecropperKey"
            v-model="form.subjectImg"
            :is-oss="isOss"
            :preview-id="uploadImg.viewId"
            :forever="true"
            :width="342"
            :view="uploadImg.view"
            :height="190"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            @changeOssPath="(path) =>{uploadImg.viewId = path}"
          />
          <image-upload4base64
            v-show="showImageUpload4base64"
            :key="uploadImg.imagecropperKey + 1"
            v-model="form.subjectImg"
            :is-oss="isOss"
            :is-base64-upload="subjectImgType === 1"
            :base64-data="selectSubjectImg.fileBase64"
            :base64-filename="selectSubjectImg.fileName"
            :forever="true"
            :width="316"
            :height="213"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            @close="showImageUpload4base64 = false"
            @changeOssPath="(path) =>{uploadImg.viewId = path,subjectImgType = 2}"
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model.trim="form.subjectKeyword" maxlength="100" placeholder="请输入关键词" />
        </el-form-item>
        <el-form-item label="标签:">
          <el-tag v-for="tag in form.subjectLabel" :key="tag" closable :disable-transitions="false" @close="handleCloseTag(tag)">{{ tag }}</el-tag>
          <br>
          <el-input ref="tagInput" v-model="tagInputValue" style="width: 50%;" class="input-new-tag" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm" />
          <span style="color: red;margin-left: 10px;display: inline-block;"><i class="el-icon-info" />输入完成后请回车</span>
        </el-form-item>
        <el-form-item label="课件来源">
          <el-input v-model.trim="form.subjectSource" maxlength="50" placeholder="请输入课件来源" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="form.subjectIntroduce" show-word-limit maxlength="1000" :rows="6" type="textarea" />
        </el-form-item>
      </el-form>
    </section>
    <section class="courseware-update-footer">
      <el-button style="padding: 10px 30px;" @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
    <el-dialog
      v-if="preview.state"
      v-el-drag-dialog
      :fullscreen="isFull"
      custom-class="courseware-preview"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :visible.sync="preview.state"
      title="预览"
      center
      width="600px"
      @close="preview.state=false"
    >
      <span slot="title" class="my-title">
        <span>预览</span>
        <div v-if="preview.fileType==='KCLX02'" class="full">
          <el-button size="small" type="primary" icon="el-icon-full-screen" @click="isFull=!isFull">{{ isFull? '取消全屏':'全屏' }}</el-button>
        </div>
      </span>
      <coursewareware-preview v-if="preview.state" :is-full="isFull" show-type="after" :type="preview.fileType" :file-id="preview.fileId" />
    </el-dialog>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import ImageUpload4base64 from '../components/ImageUpload4base64'
import coursewarewarePreview from '../components/CoursewarePreview'
import {
  getClassifyTree,
  update,
  get,
  upload
} from '../api/createCourseware'
import { specialText, int } from '@/utils/validate'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  name: 'CoursewareManage',
  components: { ImageUpload, coursewarewarePreview, ImageUpload4base64 },
  directives: { elDragDialog },
  filters: {
    filterTip(subjectType) {
      if (subjectType === 'KCLX01') {
        return '视频文件'
      } else if (subjectType === 'KCLX03') {
        return '音频文件'
      } else {
        return 'PDF文件'
      }
    }
  },
  data() {
    return {
      hottest: false,
      newest: false,
      loading: false,
      subjectImgType: 1, // 封面选择方式  1：从视频截图中取   2：自定义上传
      selectSubjectImg: '', // 选择的视频截图
      showImageUpload4base64: false, // 显示base64图片上传裁剪
      coverScreenshots: [],
      form: {
        id: '',
        subjectName: '',
        subjectSource: '',
        subjectClassify: '',
        subjectType: 'KCLX01',
        subjectImg: '',
        coverScreenshots: '',
        subjectIntroduce: '',
        courseId: '',
        courseIdUrl: '',
        subjectCategory: [],
        subjectLabel: [],
        subjectKeyword: '',
        subjectDuration: '',
        status: 'KCZT02'
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入课件名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字', trigger: 'blur' }
        ],
        subjectSource: [
          { required: true, message: '请输入课件来源', trigger: 'blur' }
        ],
        subjectClassify: [
          { required: true, message: '请选择课件分类', trigger: 'change' }
        ],
        subjectType: [
          { required: true, message: '请选择课件类型', trigger: 'change' }
        ],
        courseId: [
          { required: true, message: '请上传课件', trigger: 'change' }
        ],
        /* subjectIntroduce: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],*/
        subjectDuration: [
          { required: true, message: '请输入学习时长', trigger: 'blur' },
          { trigger: 'blur', validator: int }
        ]
      },
      inputDuration: true, // 是否禁用输入课件时长
      tagInputValue: '',
      createClassifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      },
      classifyOptions: [],
      showClassify: false,
      uploadFile: {
        showUpload: false,
        accept: 'video/mp4',
        chunksize: 10 * 1024 * 1024,
        file: ''
      },
      uploadImg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      preview: {
        state: false,
        fileId: '',
        fileType: 1
      },
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      isFull: false, // 预览是否全屏
      isCreate: true
    }
  },
  watch: {
    'form.classifyIds': {
      handler(newName, oldName) {
        if (this.$refs.classify) {
          this.$refs.classify.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    if (!this.$route.query.i) {
      this.$message({
        showClose: true,
        message: '参数异常！',
        type: 'warning',
        onClose: () => {
          this.$router.back()
        }
      })
    } else {
      this.getClassifyOption().then(() => {
        this.getData(this.$route.query.i)
      })
    }
  },
  methods: {
    handleCancel() {
      this.$router.replace({ path: this.$filterPath('courseware'), query: { active: this.$route.query.active }})
    },
    /**
     * 选择系统生成的封面
     */
    selectCoverImg(e) {
      this.selectSubjectImg = e
      this.showImageUpload4base64 = true
    },
    clearFile() {
      this.uploadFile.file = ''
      this.form.courseId = ''
      this.form.subjectDuration = ''
    },
    /**
       * 预览
       */
    handlePreview() {
      this.preview.fileId = this.form.courseIdUrl
      this.preview.fileType = this.form.subjectType
      this.preview.state = true
    },
    /**
       * 格式化课件时长单位
       */
    fomatterTimeAndPage(t) {
      if (this.form.subjectType === 'KCLX02') {
        return t + '页'
      } else {
        const fTime = t || 0
        let time = parseInt(fTime) + '秒'
        if (parseInt(fTime) > 60) {
          var second = parseInt(fTime) % 60
          var min = parseInt(fTime / 60)
          time = min + '分' + second + '秒'

          if (min > 60) {
            min = parseInt(fTime / 60) % 60
            var hour = parseInt(parseInt(fTime / 60) / 60)
            time = hour + '小时' + min + '分' + second + '秒'

            if (hour > 24) {
              hour = parseInt(parseInt(fTime / 60) / 60) % 24
              var day = parseInt(parseInt(parseInt(fTime / 60) / 60) / 24)
              time = day + '天' + hour + '小时' + min + '分' + second + '秒'
            }
          }
        }
        return time
      }
    },
    /**
       * 获取课件分类
       */
    getClassifyOption() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'JNZQFL01' }).then(({ data }) => {
          this.classifyOptions = data.data || []
          console.log('classifyOptions', this.classifyOptions)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    /**
       * 切换课件类型动态修改文件上传组件文件限制
       */
    changeFileAccept() {
      if (this.form.subjectType === 'KCLX01') {
        this.uploadFile.accept = 'video/mp4'
      } else if (this.form.subjectType === 'KCLX03') {
        this.uploadFile.accept = 'audio/mp3'
      } else {
        this.uploadFile.accept = '.pdf'
      }
      this.clearFile()
    },
    onSubmint() {
      /* if (!this.form.subjectImg) {
        this.$message({
          message: '请上传课件封面！',
          type: 'warning'
        })
        return
      }*/
      if (this.form.subjectLabel.join(',').length > 200 / 2) {
        this.$message.error('标签总字数不能超过100个字！')
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.form)
          params['subjectClassify'] = this.form.subjectClassify.length > 0 ? this.form.subjectClassify[this.form.subjectClassify.length - 1] : ''
          params['subjectLabel'] = params['subjectLabel'].join(',')
          return new Promise((resolve, reject) => {
            update(params).then(() => {
              this.dialogVisible = false
              loading.close()
              this.$message({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
              this.handleCancel()
            }).catch(error => {
              loading.close()
              reject(error)
            })
          })
        } else {
          return false
        }
      })
    },
    uploadSuccess(id, files) {
      if (id) {
        this.form.courseId = id
        this.uploadFile.file = files[0]
        if (this.form.subjectType === 'KCLX02' && files[0].totalPages && files[0].totalPages > 0) {
          this.form.subjectDuration = files[0].totalPages
        } else if (this.form.subjectType !== 'KCLX02' && files[0].duration && files[0].duration > 0) {
          this.form.subjectDuration = files[0].duration
        } else {
          this.inputDuration = false
          this.$alert('课件格式不支持，请重新上传。', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.clearFile()
            }
          })
        }
      }
    },

    /**
       * 确认课件标签输入框内容
       */
    handleInputConfirm() {
      const inputValue = this.tagInputValue.trim()
      if (inputValue) {
        this.form.subjectLabel.push(inputValue)
      }
      this.tagInputVisible = false
      this.tagInputValue = ''
    },
    /**
       * 确认课件标签
       */
    handleCloseTag(tag) {
      this.form.subjectLabel.splice(this.form.subjectLabel.indexOf(tag), 1)
    },
    /**
       * 根编辑回显
       */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            if (key === 'subjectImg') {
              this.form[key] = data.subjectImg
              this.uploadImg.viewId = this.isOss ? data.subjectImgUrl : data.subjectImg
            } else if (key === 'subjectClassify') {
              const idsArr = (data.subjectClassifyIds && data.subjectClassifyIds.split(',')) || []
              this.form[key] = idsArr
            } else if (key === 'subjectLabel') {
              this.form[key] = (data.subjectLabel && data.subjectLabel.split(',')) || []
            } else if (key === 'courseId') {
              this.form[key] = data.courseId
              this.$set(this.uploadFile, 'file', {
                name: '已上传',
                id: data.courseId
              })
            } else if (key === 'coverScreenshots') {
              this.coverScreenshots = data.coverScreenshots || []
            } else {
              this.form[key] = data[key]
            }
          }
          if (this.form.subjectType === 'KCLX01') {
            this.uploadFile.accept = 'video/mp4'
          } else if (this.form.subjectType === 'KCLX03') {
            this.uploadFile.accept = 'audio/mp3'
          } else {
            this.uploadFile.accept = '.pdf'
          }
          if (this.form.subjectType === 'KCLX02') {
            this.subjectImgType = 2
          } else {
            this.subjectImgType = data.subjectImg ? 2 : 1 // 选过封面就认为是自定义上传
          }
          this.$nextTick(() => {
            this.showClassify = true
          })
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.courseware-update {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .courseware-update-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .courseware-update-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
    .form {
      width: 1000px !important;
      margin: 0 auto;
      .el-select {
        width: 100%;
      }
      .coverScreenshots-images {
        display: flex;
        flex-wrap: wrap;
        align-items: flex-start;
        .coverScreenshots-item {
          width: 190px;
          display: inline-block;
          margin-right: 10px;
          cursor: pointer;
          img {
            width: 100%;
            height: auto;
          }
        }
      }

      .line {
        text-align: center;
      }
    }
    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;
      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }
    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
    }
  }

  .courseware-update-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
  .courseware-preview {
    .el-dialog__body{
      position: relative;
      .full{
        position: absolute;
        width: 100px;
        height: 58px;
        right: 50px;
        top: -58px;
        display: flex;
        align-items: center;
        text-align: right;
      }
    }
  }
}
</style>
<style lang="scss">
.courseware-update {
  .classify-tree-con {
    position: relative;
    height: 400px;
    overflow: hidden;
    .classify-tree-con-scrollbar {
      overflow: hidden;
      .el-scrollbar__wrap {
        max-height: 381px;
      }
    }
    .custom-tree-node {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      width: 100%;
      .tree-node-txt {
        flex: 1;
      }
    }
  }
  .el-tag--medium {
    line-height: 32px;
    height: 32px;
    & + .el-tag--medium {
      margin-left: 10px;
    }
  }
   .my-title{
   width: 100%;
   display:inline-block;
    font-size: 16px !important;
    font-family: PingFangSC-Medium !important;
    font-weight: 700 !important;
    color: #333333 !important;
      position: relative;
    .full{
      position: absolute;
      width: 100px;
      height: 58px;
      right: 50px;
      top: -18px;
      display: flex;
      align-items: center;
      text-align: right;
    }
 }
}
</style>
